package com.khotyn.heresy.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.Album;
import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.exception.IllegalUrlParamException;
import com.khotyn.heresy.service.AlbumService;

/**
 * 相册中心控制类
 * 
 * @author 黄挺
 */
@Controller
@RequestMapping("/album.html")
public class AlbumController {
	@Autowired
	AlbumService albumService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpSession session, HttpServletRequest request, @RequestParam(value = "albumID", required = false) String albumIDStr) {
		Integer userID = (Integer) session.getAttribute("userID");
		HeresyErrorMessage message = null;
		Album album = null;

		try {
			validate(albumIDStr);
		} catch (IllegalUrlParamException e) {
			return e.getErrorModel();
		}

		Integer albumID = Integer.parseInt(albumIDStr);

		try {
			album = albumService.doService(albumID, userID);
		} catch (Exception e) {
			message = new HeresyErrorMessage(e.getMessage(), "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}

		session.setAttribute("albumID", albumID);
		return new ModelAndView("album", "album", album);
	}

	private void validate(String albumIDStr) throws IllegalUrlParamException {
		HeresyErrorMessage errorMessage = null;
		if (!NumberUtils.isDigits(albumIDStr)) {
			errorMessage = new HeresyErrorMessage("非法的参数", "操作失败", "/Dragonfly/");
		}

		if (errorMessage != null) {
			throw new IllegalUrlParamException(errorMessage);
		}
	}
}
